package com._51doit.jdbc;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.sql.*;

/**
 * @Date 2021/8/24
 * @Created by HANGGE
 * @Description TODO
 */
public class JDBCTest {
    Connection conn = null ;
    Statement stm = null;
    @Before
    public void init() {
        try {
            // 1 注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 2获取连接
            // 设置数据传输编码为UTF8 支持中文
             conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_doit26?characterEncoding=utf8", "root", "root");
            // 3获取执行sql的对象
            stm = conn.createStatement();
        } catch (Exception e) {

        }
    }
    /**
     * 更新数据
     */
    @Test
    public void testUpdate() {
        try {
            String sql = "update user set name = '小刘' where uid = 111";
            stm.executeUpdate(sql);
        } catch (Exception throwables) {
            throwables.printStackTrace();
        }
    }

    /**
     * 删除数据
     */
    @Test
    public void testDelete() {
        try {
            String sql = "delete from user where uid = 111";
            stm.executeUpdate(sql);
        } catch (Exception throwables) {
            throwables.printStackTrace();
        }
    }
    @Test
    public void testInsert(){
        PreparedStatement ps = null ;
        try {
             ps = conn.prepareStatement("insert into user values(?,?)");
            ps.setInt(1,3);
            ps.setString(2 , "小流氓");
            int i = ps.executeUpdate();
            System.out.println(i);
        } catch (Exception throwables) {
            throwables.printStackTrace();
        }finally {
            try {
                ps.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }


    }


    @After
    public void after() {
        try {
            stm.close();
            conn.close();
        } catch (Exception throwables) {
            throwables.printStackTrace();
        }

    }


}
